package com.sena.engine.snmp.handler;

import com.sena.engine.common.exception.SenaSnmpRunTimeException;
import com.sena.engine.enums.SnmpResultCodeEnum;
import com.sena.engine.snmp.utils.SnmpUtils;
import net.percederberg.mibble.MibValueSymbol;
import net.percederberg.mibble.snmp.SnmpObjectType;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;

/**
 * @author Admin
 */

public class SetHandler {


    public void setValue(String oid, String nodeOid, String value, Snmp snmp, Target target) throws SenaSnmpRunTimeException {
        try {
            MibValueSymbol mibValueSymbol = SnmpUtils.getMibSymbolByOid(oid);
            SnmpObjectType snmpObjectType = (SnmpObjectType) mibValueSymbol.getType();
            Variable var = SnmpUtils.getVariable(snmpObjectType.getSyntax(), value);
            PDU pdu = SnmpUtils.createPdu(target.getVersion());
            pdu.add(new VariableBinding(new OID(oid + "." + nodeOid), var));
            ResponseEvent responseEvent = snmp.set(pdu, target);
            SnmpUtils.checkSnmpError(responseEvent);
            PDU respond = responseEvent.getResponse();
            VariableBinding variableBinding = respond.get(0);
            Variable variable = variableBinding.getVariable();
            String str = variable.toString();
            if (str.equalsIgnoreCase("noSuchInstance") ||
                    str.equalsIgnoreCase("No such name") ||
                    str.equalsIgnoreCase("noSuchObject")) {
                throw new SenaSnmpRunTimeException(SnmpResultCodeEnum.SERVER_NODE_NOT_FOUND);
            }
        } catch (Exception exception) {
            String msg = "修改 oid的值出错,oid名:" + oid + ",错误:" + exception.getMessage();
            throw new SenaSnmpRunTimeException(msg);
        } finally {
            SnmpUtils.closeSnmp(snmp);
        }
    }

    /**
     * 设置
     *
     * @param oid
     * @param variable
     * @param snmp
     * @param target
     * @throws SenaSnmpRunTimeException
     */
    public void setValue(String oid, Variable variable, Snmp snmp, Target target) throws SenaSnmpRunTimeException {
        try {
            PDU pdu = SnmpUtils.createPdu(target.getVersion());
            pdu.add(new VariableBinding(new OID(oid), variable));
            ResponseEvent event = snmp.set(pdu, target);
            SnmpUtils.checkSnmpError(event);
            snmp.close();
        } catch (Exception e) {
            String msg = "修改 oid的值出错,oid名:" + snmp + ",错误:" + e.getMessage();
            throw new SenaSnmpRunTimeException(msg);
        } finally {
            SnmpUtils.closeSnmp(snmp);
        }
    }

}
